import component from './index.vue'


export class DynamicMount {
  constructor(Vue) {
    this.instance = null
    this.InstanceConstructor = Vue.extend(component)
  }
  mount() {
    if (this.instance) {
      return
    }
    this.instance = new this.InstanceConstructor({
      data() {
        return {
          text: 'A string in component.'
        }
      },
      destroyed() {
        this.$el.parentNode.removeChild(this.$el) // 移除dom
      },
    })
    this.instance.$mount()
    document.body.appendChild(this.instance.$el)
    console.log('mount', this)
  }
  unmount() {
    if (!this.instance) {
      return
    }
    this.instance.$destroy(true)
    this.instance = null
    console.log('unmount', this)
  }

  update(data = {}) {
    if (!this.instance) {
      this.mount()
    }
    const {text} = data
    this.instance.text = text
    console.log('update', data)
  }
}

export default {
  install(Vue) {
    Vue.prototype.$dynamicMount = new DynamicMount(Vue)
  }
}